//
//  CustomMessageImageCell.m
//  FFMall
//
//  Created by ale tan on 2017/10/10.
//  Copyright © 2017年 IT.Bear. All rights reserved.
//

#import "CustomMessageImageCell.h"
#import "Masonry.h"
#import "UIImageView+WebCache.h"
#import "CAShapeLayer+ViewMask.h"
#import "ESPictureBrowser.h"
#import "FFTools.h"
#import "JMUIChattingViewController.h"

@interface CustomMessageImageCell ()<ESPictureBrowserDelegate>
{
    /**
     *  @brief  图片所在ImageView
     */
    UIImageView *mImageView;
}

@property (nonatomic ,strong) ESPictureBrowser *browser;//图片浏览器

@property (nonatomic ,assign) CGRect currentRect;

@end

@implementation CustomMessageImageCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    
    if (self)
    {
        mImageView = [UIImageView new];
        mImageView.backgroundColor = [UIColor clearColor];
        mImageView.contentMode = UIViewContentModeScaleAspectFit;
        mImageView.userInteractionEnabled = NO;
        
        mImageView.layer.masksToBounds = YES;
        mImageView.layer.cornerRadius = 3;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageBeenTaped:)];
        [bubbleImageView addGestureRecognizer:tap];
        
//        [self.contentView insertSubview:mImageView atIndex:0];
        [self.contentView addSubview:mImageView];
    }
    
    return self;
}


-(void)setModel:(JMUIChatModel *)model
{
    JMSGCustomContent *content = (JMSGCustomContent *)model.message.content;
    
    [mImageView sd_setImageWithURL:[NSURL URLWithString:content.customDictionary[@"content"]] placeholderImage:[UIImage imageNamed:@"leftMenuBk"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        CGFloat aspect = image.size.width/image.size.height;

        if (!isReceived)//是我自己发送的
        {
            [mImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(self.contentView.mas_top).offset(TopEdge);
                make.bottom.mas_equalTo(self.contentView.mas_bottom).offset(-BottomEdge);
                make.centerY.mas_equalTo(self.contentView.mas_centerY);
                make.right.mas_equalTo(headerView.mas_left).offset(-ContentToBubbleHead);
                make.left.mas_greaterThanOrEqualTo(self.contentView.mas_left).offset(ContentToEdge);
                make.width.mas_equalTo(mImageView.mas_height).multipliedBy(aspect);
            }];
            
            [bubbleImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(mImageView.mas_top).offset(-ContentToBubble);
                make.bottom.mas_equalTo(mImageView.mas_bottom).offset(ContentToBubble);
                make.left.mas_equalTo(mImageView.mas_left).offset(-ContentToBubble);
                make.right.mas_equalTo(mImageView.mas_right).offset(ContentToBubbleHead-2);
            }];
            
        }else//别人发送的消息
        {
            [mImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(self.contentView.mas_top).offset(TopEdge);
                make.bottom.mas_equalTo(self.contentView.mas_bottom).offset(-BottomEdge);
                make.left.mas_equalTo(headerView.mas_right).offset(ContentToBubbleHead);
                make.right.mas_lessThanOrEqualTo(self.contentView.mas_right).offset(-ContentToEdge-ContentToBubble);
                make.width.mas_equalTo(mImageView.mas_height).multipliedBy(aspect);
            }];
            
            [bubbleImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(mImageView.mas_top).offset(-ContentToBubble);
                make.bottom.mas_equalTo(mImageView.mas_bottom).offset(ContentToBubble);
                make.right.mas_equalTo(mImageView.mas_right).offset(ContentToBubble);
                make.left.mas_equalTo(mImageView.mas_left).offset(-ContentToBubbleHead+2);
            }];
        }
        
    }];
    
    [super setModel:model];
}


-(void)imageBeenTaped:(UITapGestureRecognizer*)tap
{
    [self routerEventWithType:EventChatCellImageTapedEvent userInfo:@{kModelKey:self.model}];
    
    [self clickToCheckImages];
}

- (void)clickToCheckImages{
    if (!_browser) {
        _browser = [[ESPictureBrowser alloc]init];
        _browser.delegate = self;
    }
    
    UINavigationController *navi = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    JMUIConversationViewController *chatVC = (JMUIConversationViewController *)navi.topViewController;
    NSArray *images = chatVC.messageDatasource.customMsgImages;
    
    JMSGCustomContent *content = (JMSGCustomContent *)self.model.message.content;
    NSString *currentImageUrl = content.customDictionary[@"content"];
    
    NSInteger currentIndex = 0;
    for (int i=0; i<images.count; i++) {
        NSString *imageUrl = images[i];
        if ([imageUrl isEqual:currentImageUrl]) {
            currentIndex = i;
            break;
        }
    }
    
    CGRect imageRect = [self.contentView convertRect:mImageView.frame toView:self];
//    CGRect contentRect = [self convertRect:imageRect toView:self.superview];
//    CGRect cellRect = [self.superview convertRect:self.frame toView:self.superview];
    //cell在当前屏幕的位置
    _currentRect = [self.superview convertRect:imageRect toView:chatVC.view];
    _browser.originPoint = _currentRect.origin;
    [_browser showFormView:chatVC.view picturesCount:images.count currentPictureIndex:currentIndex];
}

#pragma mark - ESPictureBrowserDelegate
- (UIView *)pictureView:(ESPictureBrowser *)pictureBrowser viewForIndex:(NSInteger)index
{
    UINavigationController *navi = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    JMUIConversationViewController *chatVC = (JMUIConversationViewController *)navi.topViewController;
    NSArray *images = chatVC.messageDatasource.customMsgImages;
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:mImageView.frame];
    [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",images[index]]] placeholderImage:nil];
    imageView.userInteractionEnabled = YES;
    return imageView;
}

- (NSString *)pictureView:(ESPictureBrowser *)pictureBrowser highQualityUrlStringForIndex:(NSInteger)index {
    UINavigationController *navi = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    JMUIConversationViewController *chatVC = (JMUIConversationViewController *)navi.topViewController;
    NSArray *images = chatVC.messageDatasource.customMsgImages;
    
    return images[index];
}

#pragma mark
-(void)longPress:(UILongPressGestureRecognizer *)Press
{
    if (Press.state == UIGestureRecognizerStateBegan)
    {
        [self becomeFirstResponder];
        
        UIMenuItem *copy = [[UIMenuItem alloc]initWithTitle:@"复制" action:@selector(menuCopy:)];
        UIMenuItem *remove = [[UIMenuItem alloc]initWithTitle:@"删除" action:@selector(menuRemove:)];
        
        UIMenuController *menu = [UIMenuController sharedMenuController];
        [menu setMenuItems:@[copy,remove]];
        [menu setTargetRect:bubbleImageView.frame inView:self];
        [menu setMenuVisible:YES animated:YES];
        
    }
}

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    return  ((action == @selector(menuCopy:))  || (action == @selector(menuRemove:)));
}


#pragma mark --复制、删除处理
-(void)menuCopy:(id)sender
{
    [UIPasteboard generalPasteboard].image = mImageView.image;
}

-(void)menuRemove:(id)sender
{
    [self routerEventWithType:EventChatCellRemoveEvent userInfo:@{kModelKey:self.model}];
}


@end
